import { defineConfig, loadEnv } from "vite";
import uni from "@dcloudio/vite-plugin-uni";
import type { ConfigEnv } from "vite";
import { convertEnv, getRootPath, getSrcPath } from "./build/utils";
import { createViteProxy } from "./build/config";
import AutoImport from "unplugin-auto-import/vite";
import Components from "@uni-helper/vite-plugin-uni-components";
import { NutResolver } from "nutui-uniapp";

// https://vitejs.dev/config/
export default defineConfig(async (configEnv: ConfigEnv) => {
  const UnoCss = await import("unocss/vite").then((i) => i.default);
  const srcPath = getSrcPath();
  const rootPath = getRootPath();
  const viteEnv = convertEnv(loadEnv(configEnv.mode, process.cwd()));
  const { VITE_PORT, VITE_USE_PROXY, VITE_PROXY_TYPE } = viteEnv;
  return {
    server: {
      host: "0.0.0.0",
      port: VITE_PORT,
      open: false,
      proxy: createViteProxy(VITE_USE_PROXY, VITE_PROXY_TYPE),
    },
    resolve: {
      alias: {
        "~": rootPath,
        "@": srcPath,
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@import "nutui-uniapp/styles/variables.scss";`,
        },
      },
    },
    build: {
      target: "es6",
      cssTarget: "chrome61",
      reportCompressedSize: false,
      sourcemap: false,
      chunkSizeWarningLimit: 1024, // chunk 大小警告的限制（单位kb）
      commonjsOptions: {
        ignoreTryCatch: false,
      },
      watch: {
        exclude: ["node_modules/**", "/__uno.css"],
      },
    },
    envPrefix: ["VITE_", "UNI_"],
    optimizeDeps: {
      exclude: ["vue-demi"],
    },
    plugins: [
      // https://github.com/unocss/unocss
      UnoCss(),
      AutoImport({
        imports: [
          "vue",
          "uni-app",
          "pinia",
          {
            "nutui-uniapp/composables": [
              // 在这里添加需要自动导入的API
              "useToast",
            ],
          },
        ],
      }),
      Components({
        resolvers: [NutResolver()],
      }),
      uni(),
    ],
  };
});
